/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cageballcommon.io.impl;

import cageballcommon.io.interfaces.CageballWriter;
import cageballcommon.exceptions.CageballIOException;
import cageballcommon.messages.Action;
import cageballcommon.messages.InitTeam;
import cageballcommon.messages.State;
import com.google.gson.Gson;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Properties;

/**
 *
 * @author kanonas
 */
public class CageballSocketWriter implements CageballWriter {

    private Socket socket;
    private PrintWriter out;
    private Gson gson;

    public CageballSocketWriter(Socket socket) throws IOException {
        this.socket = socket;

        out = new PrintWriter(socket.getOutputStream(), true);

        gson = new Gson();
    }

    public void writeState(State state) throws CageballIOException {
        write(state);
    }

    public void writeAction(Action action) throws CageballIOException {
        write(action);
    }

    public void writeInitTeam(InitTeam initTeam) throws CageballIOException {
        write(initTeam);
    }

    public void writeProperties(Properties properties) throws CageballIOException {
        write(properties);
    }

    public void close() throws CageballIOException {

        try {
            out.close();
            socket.close();
        } catch (IOException ex) {
            throw new CageballIOException(ex.getMessage());
        }
    }

    public void closeStream() {

        out.close();
    }

    private void write(Object o) throws CageballIOException {
        out.println(gson.toJson(o));

        if (out.checkError()) {
            throw new CageballIOException("Error writing data");
        }
    }
}
